package com.eonmind.knowledge.controller;

import com.eonmind.common.contract.data.response.ResponseEntity;
import com.eonmind.common.contract.enums.knowledge.FileUploadStatusEnum;
import com.eonmind.common.contract.enums.oss.OssBucketEnum;
import com.eonmind.common.contract.enums.oss.OssUploadEnum;
import com.eonmind.common.contract.oss.OssUtil;
import com.eonmind.common.contract.oss.dto.OssDto;
import com.eonmind.common.provider.entity.knowledge.Knowledge;
import com.eonmind.common.security.annotations.UserInfo;
import com.eonmind.knowledge.core.AsyncTaskService;
import com.eonmind.knowledge.core.BailianKnowledgeService;
import com.eonmind.knowledge.dto.KnowledgeUploadFileDto;
import com.eonmind.knowledge.mapper.KnowledgeMapper;
import com.eonmind.knowledge.service.KnowledgeService;
import com.eonmind.knowledge.service.KnowledgeUploadFileService;
import com.eonmind.user.contract.dto.UserInfoData;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.List;

import static com.eonmind.common.contract.constants.knowledge.KnowledgeConstant.KNOWLEDGE_FILE_PATH;

/**
 * @Author: AKang
 * @Description:
 * @CreateTime: 2025-05-28
 */
@RestController
@RequestMapping("/knowledge/file")
public class KnowledgeUploadFileController {

    @Resource
    private OssUtil ossUtil;
    @Resource
    private BailianKnowledgeService bailianKnowledgeService;
    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private KnowledgeUploadFileService knowledgeUploadFileService;
    @Resource
    private KnowledgeMapper knowledgeMapper;
    @Resource
    private AsyncTaskService asyncTaskService;

    /**
     * 获取用户临时访问凭证
     *
     * @param userInfoData
     * @return
     * @ignoreParams userInfoData
     */
    @UserInfo
    @PostMapping("/sts")
    public ResponseEntity<OssDto.StsResponse> userStsToken(UserInfoData userInfoData) {
        String filePath = MessageFormat.format(KNOWLEDGE_FILE_PATH.substring(1), userInfoData.getId());
        OssDto.StsResponse stsResponse = ossUtil.GetAccessCredentials(OssBucketEnum.KNOWLEDGE_BUCKET, filePath);
        return ResponseEntity.success(stsResponse);
    }

    /**
     * 上传文件到百炼知识库并将文件相关信息保存到数据库中
     *
     * @param userInfoData
     * @param knowledgeFileUploadRequests
     * @return
     * @ignoreParams userInfoData
     */
    @UserInfo
    @PostMapping("/uploadToBailian")
    public ResponseEntity<String> uploadFile(UserInfoData userInfoData, @RequestBody KnowledgeUploadFileDto.KnowledgeUploadFileRequest knowledgeFileUploadRequests) {
        Long userId = userInfoData.getId();
        Long id = knowledgeFileUploadRequests.getId();
        Knowledge knowledge = knowledgeMapper.getKnowledgeById(id);
        if (ObjectUtils.isEmpty(knowledge) || ObjectUtils.compare(knowledge.getUserId(), userInfoData.getId()) != 0) {
            return ResponseEntity.fail("上传文件失败,所操作知识库非法!");
        }
        String indexId = knowledge.getIndexId();
        List<KnowledgeUploadFileDto.FileNames> fileNames = knowledgeFileUploadRequests.getFileNames();

        //注入userId和indexId
        KnowledgeUploadFileDto.KnowledgeFile knowledgeFile = new KnowledgeUploadFileDto.KnowledgeFile();
        knowledgeFile.setUserId(userId);
        knowledgeFile.setIndexId(indexId);


        for (KnowledgeUploadFileDto.FileNames fileName : fileNames) {
            Long userIdByIndexId = knowledgeMapper.getUserIdByIndexId(indexId);
            if (!userIdByIndexId.equals(userId)) {
                throw new RuntimeException("上传文件失败,所操作知识库非法!");
            }
            //注入文件原始名
            knowledgeFile.setOriginalName(fileName.getOriginalName());
            knowledgeFile.setRealName(fileName.getRealName());
            knowledgeFile.setUserId(userId);
            knowledgeFile.setIndexId(indexId);
            //获取文件上传后的OSS访问url
            String fileUrl = bailianKnowledgeService.getFileUrl(OssUploadEnum.KNOWLEDGE_FILE_UPLOAD, fileName.getRealName(), userId);
            knowledgeFile.setFileUrl(fileUrl);
            knowledgeFile.setFileStatus(FileUploadStatusEnum.UPLOAD_PROCESSING.getCode());
            //先保存文件基本信息(无需通过上传后才能获取的)
            knowledgeUploadFileService.saveKnowledgeUploadFile(knowledgeFile);

            //再异步上传文件至百炼知识库,并更新文件上传后才有的信息
            asyncTaskService.importToBailianAsync(knowledgeFile);
        }
        return ResponseEntity.success("上传成功,正在导入中....");
    }


}
